//
//  WHGetMoneyController.m
//  SquirrelSeller
//
//  Created by 邓伟浩 on 2019/1/13.
//  Copyright © 2019 邓伟浩. All rights reserved.
//

#import "WHGetMoneyController.h"
#import "WHInputInfoCell.h"
#import "NSString+WH3DES.h"
#import "WHBankInfoView.h"
#import "WHBankInfoController.h"
#import "WHCodeInfoCell.h"
#import "WHPayPasswordController.h"

@interface WHGetMoneyController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *dataTableView;
@property (nonatomic, strong) NSArray *tipsArray;
@property (nonatomic, strong) NSArray *placeHolderArray;
@property (nonatomic, strong) NSMutableArray *useInfoArray;

@property (nonatomic, strong) WHBankInfoView *bankInfoView;

@end

@implementation WHGetMoneyController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.naviType = NaviTypeClear;
    
    self.navigationItem.title = @"提现";
    [self initParams];
    [self setUpTableView];
    [self selectBankCard];
}

- (void)initParams {
    _tipsArray = @[@"提现金额", @"手机号码", @"支付密码"];
    _placeHolderArray = @[@"请输入金额", @"请输入手机号码", @"请输入支付密码"];
    _useInfoArray = @[@"", userManager.detailUserInfo.mobile, @""].mutableCopy;
}

- (void)setUpTableView {
    UITableView *dataTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:dataTableView];
    dataTableView.delegate = self;
    dataTableView.dataSource = self;
    dataTableView.tableFooterView = [self tableFootView];
    dataTableView.tableHeaderView = [self tableHeaderView];
    dataTableView.bounces = NO;
    
    [dataTableView registerClass:[WHInputInfoCell class] forCellReuseIdentifier:NSStringFromClass([WHInputInfoCell class])];
    [dataTableView registerClass:[WHCodeInfoCell class] forCellReuseIdentifier:NSStringFromClass([WHCodeInfoCell class])];
    dataTableView.backgroundColor = CViewBgMainColor;
    dataTableView.separatorColor = CLineColor;
    dataTableView.separatorInset = UIEdgeInsetsMake(0, KNormalSpace, 0, -KNormalSpace);
    
    [dataTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_top);
    }];
    _dataTableView = dataTableView;
}

- (UIView *)tableHeaderView {
    UIView *tableHeaderView = [[UIView alloc] init];
    tableHeaderView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(330)+kTopHeight);
    
    UIImageView *topBackImageView = [[UIImageView alloc] init];
    [tableHeaderView addSubview:topBackImageView];
    topBackImageView.image = IMAGE_NAMED(@"getMoney_back");
    topBackImageView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(300));
    
    UIView *topBackView = [[UIView alloc] init];
    [tableHeaderView addSubview:topBackView];
//    topBackView.backgroundColor = KWhiteColor;
    topBackView.frame = CGRectMake(0, kTopHeight, KScreenWidth, kRealwidth(120));
    
    UILabel *tipsLabel = [[UILabel alloc] init];
    [topBackView addSubview:tipsLabel];
    tipsLabel.textColor = KWhiteColor;
    tipsLabel.text = @"余额（元）";
    tipsLabel.textAlignment = NSTextAlignmentCenter;
    tipsLabel.font = SYSTEMFONT(kRealwidth(15));
    [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(topBackView);
        make.height.mas_equalTo(kRealwidth(15));
        make.top.mas_equalTo(topBackView.mas_top).offset(kRealwidth(30));
    }];
    
    UILabel *moneyLabel = [[UILabel alloc] init];
    [topBackView addSubview:moneyLabel];
    moneyLabel.textColor = KWhiteColor;
    moneyLabel.text = userManager.balance;
    moneyLabel.textAlignment = NSTextAlignmentCenter;
    moneyLabel.font = SYSTEMFONT(kRealwidth(36));
    moneyLabel.adjustsFontSizeToFitWidth = YES;
    [moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(topBackView);
        make.height.mas_equalTo(kRealwidth(36));
        make.top.mas_equalTo(tipsLabel.mas_bottom).offset(kRealwidth(20));
    }];
    
    
    WHBankInfoView *bankInfoView = [[WHBankInfoView alloc] init];
    bankInfoView.frame = CGRectMake(0, topBackView.bottom, KScreenWidth, kRealwidth(210));
    _bankInfoView = bankInfoView;
    
    [tableHeaderView addSubview:bankInfoView];
    
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toBankInfo)];
    [bankInfoView addGestureRecognizer:tapGes];
    
    return tableHeaderView;
}

- (UIView *)tableFootView {
    UIView *tableFootView = [[UIView alloc] init];
    tableFootView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(85));
    
    UIButton *submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    submitButton.frame = CGRectMake(kRealwidth(32), kRealwidth(20), KScreenWidth-2*kRealwidth(32), kRealwidth(45));
    ViewRadius(submitButton, kRealwidth(45)/2);
    [tableFootView addSubview:submitButton];
    NSString *logoutTitle = @"提现";
    NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:logoutTitle attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(17)), NSForegroundColorAttributeName:KWhiteColor}];
    [submitButton setAttributedTitle:attributeStr forState:UIControlStateNormal];
    submitButton.backgroundColor = CMDarkOrangeColor;
    [submitButton addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    
    return tableFootView;
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource ——————

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _placeHolderArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 2) {
        WHCodeInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHCodeInfoCell class]) forIndexPath:indexPath];
        cell.tipsLabel.text = _tipsArray[indexPath.row];
        cell.messageField.text = _useInfoArray[indexPath.row];
        [cell setInputTextPlaceHolder:_placeHolderArray[indexPath.row]];
        [cell.rightTipsButton setTitle:@"忘记密码?" forState:UIControlStateNormal];
        kWeakSelf(self);
        cell.textChangeBlock = ^(NSString *text) {
            [weakself.useInfoArray replaceObjectAtIndex:indexPath.row withObject:text];
        };
        cell.rightBtnClicked = ^{
            [weakself toSetPayPassword];
        };
        cell.contentView.backgroundColor = CViewBgMainColor;
        
        return cell;
    } else {
        WHInputInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHInputInfoCell class]) forIndexPath:indexPath];
        cell.tipsLabel.text = _tipsArray[indexPath.row];
        cell.messageField.text = _useInfoArray[indexPath.row];
        [cell setInputTextPlaceHolder:_placeHolderArray[indexPath.row]];
        
        kWeakSelf(self);
        cell.textChangeBlock = ^(NSString *text) {
            [weakself.useInfoArray replaceObjectAtIndex:indexPath.row withObject:text];
        };
        if (indexPath.row == 0) {
            cell.validType = ValideTypeAmount;
            cell.messageField.enabled = YES;
        } else if (indexPath.row == 1) {
            cell.validType = ValideTypePhoneNumber;
            cell.messageField.enabled = NO;
        }
        cell.contentView.backgroundColor = CViewBgMainColor;
        
        return cell;
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(55);
}

#pragma mark - —————— 事件 ——————

- (void)toSetPayPassword {
    WHPayPasswordController *payPassword = [[WHPayPasswordController alloc] init];
    [self.navigationController pushViewController:payPassword animated:YES];
}

- (void)submit:(UIButton *)button {
    [self.view endEditing:YES];
    NSString *amount = _useInfoArray[0];
    NSString *phone = _useInfoArray[1];
    NSString *payPassword = _useInfoArray[2];
    
    if (amount.doubleValue > userManager.balance.doubleValue) {
        [WHView showMessage:@"余额不足,请重新输入!" inView:self.view];
        [_useInfoArray replaceObjectAtIndex:0 withObject:@""];
        [self.dataTableView reloadData];
        return;
    }
    
    if (amount.length == 0 || phone.length == 0 || payPassword.length == 0) {
        [WHView showMessage:@"请完善以上信息" inView:self.view];
        return;
    }
    if (payPassword.length != 6) {
        [WHView showMessage:@"请输入6位支付密码" inView:self.view];
        return;
    }
    
    [self withDraw];
}

- (void)toBankInfo {
    WHBankInfoController *bankInfo = [[WHBankInfoController alloc] init];
    [self.navigationController pushViewController:bankInfo animated:YES];
}

#pragma mark - —————— 接口 ——————

- (void)selectBankCard {
    if (userManager.bankModel) {
        _bankInfoView.bankModel = userManager.bankModel;
        return;
    }
    
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_selectBanckCard);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *code = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (code.intValue == 0) {
                NSDictionary *retDict = responseObject[@"retobj"];
                userManager.bankModel = [WHBankModel modelWithDictionary:retDict];
                _bankInfoView.bankModel = userManager.bankModel;
                
            } else {
                [WHView showHudMsg:errorMsg];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)withDraw {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_withDraw);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          _useInfoArray[0], @"amount",
                          [NSString encryptUseDES3:_useInfoArray[2] key:DES3Key], @"payPassWord",
                          nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *code = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (code.intValue == 0) {
                [WHView showAlertwithTitle:nil message:@"提现成功"];
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [WHView showHudMsg:errorMsg];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

@end
